package com.whynot.frame.ms.controller;


import com.whynot.frame.auth.jwt.utils.JWTUtil;
import com.whynot.frame.auth.shiro.cache.AuthCache;
import com.whynot.frame.auth.shiro.exception.UnauthorizedException;
import com.whynot.frame.basic.common.model.APIBase;
import com.whynot.frame.basic.common.model.ErrorCode;
import com.whynot.frame.basic.redis.service.IRedisClient;
import com.whynot.frame.basic.redis.service.impl.RedisClientImpl;
import com.whynot.frame.basic.util.StringUtils;
import com.whynot.frame.ms.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 描    述:登录接口
 * 创建时间: 2018/07/01
 */
@Api(value = "login", description  = "登录接口" )
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    AuthCache authCache;

    @PostMapping("/login")
    @ApiOperation(value = "登陆接口", notes = "登陆接口", response = APIBase.class)
    public APIBase login(
            @ApiParam(name = "username",value = "用户名",defaultValue = "admin",required = true) @RequestParam("username") String username,
            @ApiParam(name = "password",value = "密码",required = true) @RequestParam("password") String password) throws Exception {
        String authorization = userService.login(username,password);
        if (StringUtils.isNotEmpty(authorization)) {
            return new APIBase(ErrorCode.SUCCESS_CODE, "Login success", authorization,true);
        } else {
            throw new UnauthorizedException();
        }
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出接口", notes = "退出接口", response = APIBase.class)
    public APIBase logout(HttpServletRequest request ){
        String token = request.getHeader("Authorization");
        String userName = JWTUtil.getUsername(token);
        Map<String,Object> map = authCache.getUser(userName);
        if(StringUtils.isNotEmpty(map) && map.size() > 0){
            authCache.clearAllUserInfo(token);
            return  new APIBase(ErrorCode.SUCCESS_CODE,"logout success",null,true);
        }
        return  new APIBase(ErrorCode.ERR_BUS_ERROR,"logout fail,用户信息不存在",null,true);
    }


}
